package com.future.mayi.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.ToastUtil;
import com.future.mayi.R;
import com.future.mayi.activity.BaseActivity;
import com.future.mayi.activity.BaseFragment;
import com.future.mayi.activity.ChangePhoneActivity;
import com.future.mayi.app.App;
import com.future.mayi.model.PhoneAreaModel;
import com.future.mayi.response.PhoneAreaResponse;
import com.future.mayi.utils.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ChangePhoneFragment2 extends BaseFragment {

    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.edt_code)
    EditText edtCode;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.tv_phone)
    EditText tvPhone;
    @BindView(R.id.tv_area)
    TextView tvArea;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_change_phone2;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        getArea();
    }


    @OnClick({R.id.tv_get_code, R.id.tv_enter, R.id.tv_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_area: {
                CommonUtils.hideKeyboard(null, getActivity());
                selectArea();
            }
            break;
            case R.id.tv_get_code: {
                tvGetCode.setEnabled(false);
                if (TextUtils.isEmpty(tvPhone.getText())) {
                    tvGetCode.setEnabled(true);
                    ToastUtil.getInstance().show(getActivity(), "请输入手机号");
                    return;
                }
                String mobile = tvPhone.getText().toString();
                getCode(mobile);
            }
            break;
            case R.id.tv_enter: {
                tvEnter.setEnabled(false);
                if (TextUtils.isEmpty(tvPhone.getText())) {
                    tvEnter.setEnabled(true);
                    ToastUtil.getInstance().show(getActivity(), "请输入手机号");
                    return;
                }
                String mobile = tvPhone.getText().toString();
                if (TextUtils.isEmpty(edtCode.getText())) {
                    tvEnter.setEnabled(true);
                    ToastUtil.getInstance().show(getActivity(), "请输入验证码");
                    return;
                }
                String code = edtCode.getText().toString();
                if (code.length() < 4) {
                    tvEnter.setEnabled(true);
                    ToastUtil.getInstance().show(getActivity(), "请输入正确的验证码");
                    return;
                }
                check(code, mobile);
            }
            break;
        }
    }

    private void check(String code, final String mobile) {
        ((BaseActivity) getActivity()).showLoadingDialog();
        new HttpRequest<DefaultResponse>()
                .with(getActivity())
                .addParam("token", App.getToken(mContext))
                .addParam("mobile", mobile)
                .addParam("captcha", code)
                .addParam("country_id", getCountryId())
                .setApiCode(ApiCst.changemobile)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        ((BaseActivity) getActivity()).dissmissLoadingDialog();
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginPhone, mobile);
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginPhoneCountryId, getCountryId() == null ? "" : getCountryId());
                        SharedPreferencesUtils.set(getActivity(), SharedPreferencesUtils.SpEnum.LoginPhoneCountryCode, getCountryCode()==null?"":getCountryCode());
                        toast(response.message);
                        (getActivity()).finish();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        ((BaseActivity) getActivity()).dissmissLoadingDialog();
                        toast(message);
                        tvEnter.setEnabled(true);
                    }
                })
                .start(new DefaultResponse());
    }


    @SuppressWarnings("unchecked")
    private void getCode(String mobile) {
        tvGetCode.setEnabled(false);
        new HttpRequest<DefaultResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.sendCode)
                .addParam("is_new", 1)
                .addParam("mobile", mobile)
                .addParam("country_id", getCountryId())
                .addParam("event", "changemobiletwo")
                .setListener(new HttpRequest.OnNetworkListener() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        toast(response.message);
                        isRun = true;
                        new Thread(runnable).start();
                    }

                    @Override
                    public void onFail(String message, BaseResponse response) {
                        tvGetCode.setEnabled(true);
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }


    private boolean isRun = false;

    //验证码发送倒计时
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvGetCode.setEnabled(false);
                }
            });
            for (int i = 60; i > 0; i--) {
                final int finalI = i;
                if (!isRun) return;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvGetCode.setText("重新获取(" + finalI + ")");
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (!isRun) return;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvGetCode.setEnabled(true);
                    tvGetCode.setText("重新获取");
                }
            });
            isRun = false;
        }
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        isRun = false;
    }


    private List<String> phoneAreaList;
    private OptionsPickerView phoneAreaDialog;
    public List<PhoneAreaModel> phoneAreaModels;
    private PhoneAreaModel thisAreModel;

    private void getArea() {
        new HttpRequest<PhoneAreaResponse>()
                .with(mContext)
                .setApiCode(ApiCst.getCountry)
                .setListener(new HttpRequest.OnNetworkListener<PhoneAreaResponse>() {
                    @Override
                    public void onSuccess(PhoneAreaResponse baseResponse) {
                        phoneAreaModels = baseResponse.list;
                        if (phoneAreaModels == null || phoneAreaModels.size() <= 0) return;
                        phoneAreaList = new ArrayList<>();
                        for (PhoneAreaModel model : phoneAreaModels) {
                            if (model == null) continue;
                            phoneAreaList.add(model.getCountry_name() + " +" + model.getArea_code());
                        }
                    }

                    @Override
                    public void onFail(String message, PhoneAreaResponse response) {

                    }
                }).start(new PhoneAreaResponse());
    }

    private void selectArea() {
        if (phoneAreaList == null) {
            getArea();
            toast("正在获取区号");
            return;
        }
        if (phoneAreaDialog == null) {
            phoneAreaDialog = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    if (phoneAreaModels == null || phoneAreaModels.size() <= options1) return;
                    thisAreModel = phoneAreaModels.get(options1);
                    tvArea.setText("+" + thisAreModel.getArea_code());
                }
            }).setCancelColor(getResources().getColor(R.color.main_text_color))
                    .setSubmitColor(getResources().getColor(R.color.main_color))
                    .setContentTextSize(20)
                    .setTitleText("请选择国家")
                    .build();
            phoneAreaDialog.setPicker(phoneAreaList);
        }
        phoneAreaDialog.show();
    }


    public String getCountryId() {
        return thisAreModel == null ? null : String.valueOf(thisAreModel.getCountry_id());
    }

    public String getCountryCode() {
        return thisAreModel == null ? null : thisAreModel.getArea_code();
    }

}
